package com.pingsky.apm.agent.core;

import com.pingsky.apm.agent.api.AgentDir;
import com.pingsky.apm.agent.api.log.PLogger;
import com.pingsky.apm.agent.api.log.PLoggerBinder;
import com.pingsky.apm.agent.api.log.PLoggerFactory;
import com.pingsky.apm.agent.core.log.Slf4jLoggerBinder;
import com.pingsky.apm.agent.core.service.ServiceManager;
import org.apache.log4j.xml.DOMConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.lang.instrument.Instrumentation;

/**
 * 启动器,运行于agent类加载器中
 */
public class PingSkyLauncher {

    private final Logger logger;
    private final PLoggerBinder binder;
    private final Instrumentation instrumentation;

    public PingSkyLauncher(Instrumentation instrumentation) {
        this.instrumentation = instrumentation;

        AgentDir agentDir = AgentDir.getInstance();
        DOMConfigurator.configure(agentDir.getLibDir().getAbsolutePath() + File.separator + "log4j.xml");

        this.logger = LoggerFactory.getLogger(PingSkyLauncher.class);
        this.binder = new Slf4jLoggerBinder();
        bindPLoggerFactory(this.binder);
        ServiceManager.INSTANCE.boot();
    }


    private void bindPLoggerFactory(PLoggerBinder binder) {
        final String binderClassName = binder.getClass().getName();
        PLogger pLogger = binder.getLogger(binder.getClass().getName());
        pLogger.info("PLoggerFactory.initialize() bind:{} cl:{}", binderClassName, binder.getClass().getClassLoader());
        // Set binder to static LoggerFactory
        // Should we unset binder at shutdown hook or stop()?
        PLoggerFactory.initialize(binder);
    }
}
